<template>
  <a-modal
    :visible="visible"
    title="新增用户"
    cancelText="取消"
    okText="提交"
    @ok="submit"
    @cancel="cancel"
  >
    <a-form
      ref="formRef"
      :model="postForm"
    >
      <a-form-item label="题目类型">
        <a-select v-model:value="postForm.quType" :options="quTypes" :disabled="quTypeDisabled" placeholder="请选择题目类型" @change="aaa">
        </a-select>
      </a-form-item>
      <a-form-item label="难度等级">
        <a-select v-model:value="postForm.level" :options="levels" placeholder="请选择难度等级">
          <a-select-option value="1">普通</a-select-option>
          <a-select-option value="2">较难</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="归属题库">
        <a-select
          v-model:value="postForm.repoIds"
          mode="multiple"
          style="width: 100%"
          placeholder="请选择归属题库"
          :options=question
        ></a-select>
      </a-form-item>
      <a-form-item ref="content" label="题目内容" name="content">
        <a-input v-model:value="postForm.content" placeholder="Basic usage"/>
      </a-form-item>
      <a-form-item label="试题图片">
        <a-upload
          name="file"
          v-model="postForm.image"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          action="http://192.168.0.145:9292/api/sys/upload/uploadFiles"
          :before-upload="beforeUpload"
          @change="handleChange"
          :headers="headers"
        >
          <img v-if="imageUrl" :src="imageUrl" alt="avatar" width="110" height="110"/>
          <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="整题解析">
        <a-textarea v-model:value="postForm.analysis"/>
      </a-form-item>
    </a-form>

    <a-form
      ref="formRef"
      name="dynamic_form_item"
      :model="postForm.answerList"
      v-bind="formItemLayoutWithOutLabel"
      v-if="testShow"
    >
      <a-form-item
        v-for="(domain, index) in postForm.answerList"
        :key="domain.key"
        v-bind="index === 0 ? formItemLayout : {}"
        :label="index === 0 ? '选项卡' : ''"
        :name="['domains', index, 'value']"
      >
        <a-input
          v-model:value="domain.content"
          placeholder="答案内容"
          style="width: 60%; margin-right: 8px;margin-top: 10px"
        />
        <a-input
          v-model:value="domain.analysis"
          placeholder="答案解析"
          style="width: 60%; margin-right: 8px;margin-top: 10px;margin-bottom: 10px"
        />
        <!--        <a-upload-->
        <!--          name="file"-->
        <!--          v-model="domain.image"-->
        <!--          list-type="picture-card"-->
        <!--          class="avatar-uploader"-->
        <!--          :show-upload-list="false"-->
        <!--          action="http://192.168.0.145:9292/api/sys/upload/uploadFiles"-->
        <!--          :before-upload="beforeUpload"-->
        <!--          @change="handleChange_sel"-->
        <!--          :headers="headers"-->
        <!--        >-->
        <!--          <img v-if="postForm.answerList[addDomainCount].imageUrl" :src="postForm.answerList[addDomainCount].imageUrl" alt="avatar" width="80" height="80"/>-->
        <!--          <div v-else>-->
        <!--            <loading-outlined v-if="loading"></loading-outlined>-->
        <!--            <plus-outlined v-else></plus-outlined>-->
        <!--            <div class="ant-upload-text">Upload</div>-->
        <!--          </div>-->
        <!--        </a-upload>-->
        是否答案：
        <a-switch v-model:checked="domain.isRight" checked-children="开" un-checked-children="关"/>
        <MinusCircleOutlined
          v-if="postForm.answerList.length > 1"
          class="dynamic-delete-button"
          :disabled="postForm.answerList.length === 1"
          @click="removeDomain(domain)"
        />
      </a-form-item>
      <a-form-item v-bind="formItemLayoutWithOutLabel">
        <a-button type="dashed" style="width: 60%" @click="addDomain">
          <PlusOutlined/>
          添加
        </a-button>
      </a-form-item>
    </a-form>
  </a-modal>

</template>
<script>
import {message} from 'ant-design-vue';
import {list} from "@/api/module/post";
import {uploadAvatar} from "@/api/module/user";
import {defineComponent, reactive, ref, toRaw, watch} from "vue";
import {PlusOutlined, LoadingOutlined, MinusCircleOutlined} from '@ant-design/icons-vue';
import {quQuDetail, saveData} from "../../../api/module/exam";

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default defineComponent({
  components: {
    LoadingOutlined,
    PlusOutlined,
    MinusCircleOutlined,
  },
  props: {
    visible: {
      type: Boolean,
    },
    record: {
      type: Object,
    }
  },
  emit: ["close"],
  setup(props, context) {
    const fileList = ref([]);
    const loading = ref(false);
    const imageUrl = ref('');
    const formRef = ref();
    const quTypeDisabled = ref(false);
    let itemImage = true;
    let id = '';
    // 上传图片携带token
    const tokenKey = localStorage.getItem("token_key");
    const token = localStorage.getItem("token")

    // 答案框显示参数
    let testShow = ref(false)
    const state = reactive({
      posts: [],
      depts: [],
    })
    const headers = {
      "Authorization": token,
      "Authorization-key": tokenKey
    };
    // 题目内容
    let postForm = ref({
      content: '123',
      repoIds: [],
      answerList: []
    });
    let levels = [
      {value: 1, label: '普通'},
      {value: 2, label: '较难'}
    ]

    let quTypes = ref([{
      value: 1,
      label: '单选题'
    }, {
      value: 2,
      label: '多选题'
    },
      {
        value: 3,
        label: '判断题'
      }
    ])
    // 题库下拉框
    let question = [];

    const formState = reactive({
      avatar: "",
      enable: true,
      gender: "0",
    });


    watch(props, (props) => {
      id = props.record.id;
      console.log("修改传参+", id)
      if (id != 'undefined' && id != null && id != '') {
        const param = {
          id: id,
        }
        quQuDetail(param).then((response) => {
          // 使得题目类型变为无法修改状态
          quTypeDisabled.value = true
          // 修改获取页面数据
          postForm.value = response.data
          testShow.value = true
          imageUrl.value = postForm.value.image
        });
      }
    })


    const submit = (e) => {
      let rightCount = 0
      console.log("答案选项：", postForm.value.answerList)
      postForm.value.answerList.forEach(function (item) {
        if (item.isRight) {
          rightCount += 1
        }
      })
      if (postForm.value.quType == 1) {
        if (rightCount != 1) {
          message.error("单选题答案只能有一个")
          return
        }
      }

      if (postForm.value.quType == 2) {
        if (rightCount < 2) {
          message.error("多选题至少要有两个正确答案")
          return
        }
      }

      if (postForm.value.quType == 3) {
        if (rightCount != 1) {
          message.error("判断题只能有一个正确项")
          return
        }
      }
      saveData(toRaw(postForm.value)).then((response) => {
        if (response.success) {
          message.success({content: '保存成功', duration: 1}).then(() => {
            cancel();
          });
        } else {
          message.error({content: '保存失败', duration: 1}).then(() => {
            cancel();
          });
        }
      })

    };


    const cancel = (e) => {

      context.emit("close", false);
    };


    //上传题目图片
    const uploadHeadPortrait = (files) => {
      const {file} = files
      console.log("图片上传中--------------", file)
      let formData = new FormData();
      formData.append("file", file.name);
      uploadAvatar({formData}).then((response) => {
        console.log("ASDASD+++++++++", response.data);
      })

    };
    // 上传题目图片改变时的状态
    const handleChange = info => {
      if (info.file.status === 'uploading') {
        loading.value = true;
        return;
      }

      if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, base64Url => {
          imageUrl.value = base64Url;
          loading.value = false;
          console.log("图片url：", info.file.response.data.url)
          if (info.file.response.code === 200) {
            postForm.value.image = info.file.response.data.url
            message.success("上传成功")
          }
        });
      }

      if (info.file.status === 'error') {
        loading.value = false;
        message.error('upload error');
      }
    };
    // const handleChange_sel = info => {
    //   if (info.file.status === 'uploading') {
    //     loading.value = true;
    //     return;
    //   }
    //
    //   if (info.file.status === 'done') {
    //     getBase64(info.file.originFileObj, base64Url => {
    //       postForm.answerList[addDomainCount].imageUrl = base64Url;
    //       loading.value = false;
    //       console.log("图片url：", info.file.response.data.url)
    //       if (info.file.response.code === 200) {
    //         postForm.image = info.file.response.data.url
    //         message.success("上传成功")
    //       }
    //     });
    //   }
    //
    //   if (info.file.status === 'error') {
    //     loading.value = false;
    //     message.error('upload error');
    //   }
    // };
    // 上传题目图片之前的钩子
    const beforeUpload = file => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

      if (!isJpgOrPng) {
        message.error('只能上传【png/jpg】格式图片！');
      }
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isLt2M) {
        message.error('图片大小不能超过【1MB】!');
      }
      return isJpgOrPng && isLt2M;
    };


    // 获取题库列表
    const getQuestion = () => {
      // list({}).then((response) => {
      //   state.posts = response.data;
      // })
      let response = {
        "code": 0,
        "data": [
          {
            "value": "1528551814046244866",
            "label": "vbn",
          },
          {
            "value": "1531214458792210434",
            "label": "农业题库",
          }
        ],
        "msg": "操作成功！",
        "success": true
      };
      question = response.data
    }
    // 选择题库事件

    // 题目类型点击事件，用来判断答案框是否显示
    const aaa = quType => {

      postForm.value.answerList = []
      testShow.value = true
      if (quType == 3) {
        postForm.value.answerList.push({isRight: true, content: '正确', analysis: ''})
        postForm.value.answerList.push({isRight: false, content: '错误', analysis: ''})
      }

      if (quType == 1 || quType == 2) {
        postForm.value.answerList.push({isRight: false, content: '', analysis: ''})
        postForm.value.answerList.push({isRight: false, content: '', analysis: ''})
        postForm.value.answerList.push({isRight: false, content: '', analysis: ''})
        postForm.value.answerList.push({isRight: false, content: '', analysis: ''})
      }
      console.log(`selected `, quType);
    };
    // 答案选择框占比
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 4,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 20,
        },
      },
    };
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 20,
          offset: 4,
        },
      },
    };
    // 答案列表
    // 提交答案列表，已删
    // const submitForm = () => {
    //   formRef.value.validate().then(() => {
    //     console.log('values', postForm.answerList);
    //   }).catch(error => {
    //     console.log('error', error);
    //   });
    // };
    // 删除一个 选项
    const removeDomain = item => {
      let index = postForm.value.answerList.indexOf(item);

      if (index !== -1) {
        postForm.value.answerList.splice(index, 1);
      }
    };
    // 添加一个 选项
    const addDomain = () => {
      if (postForm.value.quType == 3) {
        message.error("判断题只能拥有两个选项！！！")
      } else {
        postForm.value.answerList.push({
          isRight: false, content: '', analysis: '',
        });
      }
    };

    // 进入页面就调用获取题库
    getQuestion()
    return {
      state,
      submit,
      cancel,
      formRef,
      formState,


      // 下面是上传图片所用接口
      loading,
      imageUrl,
      handleChange,
      // handleChange_sel,
      beforeUpload,
      headers,
      // addDomainCount,
      uploadHeadPortrait,


      quTypeDisabled,
      postForm,
      quTypes,
      levels,
      id,
      question,
      aaa,
      testShow,
      value: ref([]),
      formItemLayout,
      formItemLayoutWithOutLabel,
      removeDomain,
      addDomain,
    };


  },
});
</script>
<style>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}

.dynamic-delete-button:hover {
  color: #777;
}

.dynamic-delete-button[disabled] {
  float: right;
  cursor: not-allowed;
  opacity: 0.5;
}
</style>
